package com.archer.task04;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class ICyclicBarrier {
    private volatile Integer value = null;

    public static void main(String[] args) {
        long start=System.currentTimeMillis();
        // 在这里创建一个线程或线程池，
        // 异步执行 下面方法


        final ICyclicBarrier iCyclicBarrier = new ICyclicBarrier();
        CyclicBarrier barrier = new CyclicBarrier(1, ()-> {
            int result = 0; //这是得到的返回值
            try {
                result = iCyclicBarrier.getValue();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 确保  拿到result 并输出
            System.out.println("异步计算结果为："+result);

            System.out.println("使用时间："+ (System.currentTimeMillis()-start) + " ms");
        });

        Thread thread = new Thread(() -> {
            try {
                iCyclicBarrier.sum(36, barrier);
            } catch (BrokenBarrierException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();

        // 然后退出main线程
    }

    public void sum(int num, CyclicBarrier barrier) throws BrokenBarrierException, InterruptedException {
        value = fibo(num);
        barrier.await();
    }

    private int fibo(int a) {
        if ( a < 2) {
            return 1;
        }
        return fibo(a-1) + fibo(a-2);
    }

    public int getValue() throws InterruptedException {
        return value;
    }
}
